<?php
/**
 * Created by PhpStorm.
 * Author: QinShuai
 * Email: qinshuai0423@qq.com
 * Date: 2021/6/16
 */

namespace common\components;

use yii\base\InvalidConfigException;

/**
 * Class Service
 * @package common\components
 */
class Service
{
    /**
     * 已实例化子服务
     * @var
     */
    public $_services;

    /**
     * 自定义服务
     * @var
     */
    public $service;

    /**
     * 获取子服务
     * @param string $service
     * @return mixed|object|string|null
     * @throws InvalidConfigException
     */
    public function __get(string $service)
    {
        $service = ucfirst($service);
        if (!isset($this->_services[$service])) {
            if (isset($this->service[$service])) {
                $class = $this->service[$service];
            } else {
                if (!class_exists("backend\services\\" . $service . 'Service')) {
                    throw new InvalidConfigException('Service [' . $service . '] is not find in ' . get_called_class() . ', you must config it! ');
                }
                $class = "backend\services\\" . $service . 'Service';
            }

            $this->_services[$service] = \Yii::createObject($class);
        }
        return $this->_services[$service] ?? null;
    }
}